package com.icinfo.cloud.provider.common.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 签名
 *
 * @author shenlongfei
 * @create 2022-11-08 13:58
 */
public class SignatureUtil {
    public static String computeSignature(String key, String canonicalString) {
        try {
            byte[] signData = sign(key.getBytes("UTF-8"), canonicalString.getBytes("UTF-8"));
            return new String(Base64.getEncoder().encode(signData));
        } catch (UnsupportedEncodingException var3) {
            throw new RuntimeException("Unsupported algorithm: UTF-8", var3);
        }
    }

    private static byte[] sign(byte[] key, byte[] data) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(key, "HmacSHA256"));
            return mac.doFinal(data);
        } catch (NoSuchAlgorithmException var3) {
            throw new RuntimeException("Unsupported algorithm: HmacSHA256", var3);
        } catch (InvalidKeyException var4) {
            throw new RuntimeException("Invalid key: " + key, var4);
        }
    }

    public static void main(String[] args) {
        //appKey: n1kUh5Jc
        //appSecret: f63d579fc2f5dee76b2302faf2ab3737
        long currentTimeMillis = System.currentTimeMillis();
        String canonicalString = currentTimeMillis + "\n" + "f63d579fc2f5dee76b2302faf2ab3737";
        String signValue = computeSignature("f63d579fc2f5dee76b2302faf2ab3737", canonicalString);
        System.out.println(signValue);
    }
}
